/*
** convert_base.c for my_printf in /home/vanet_c//convert_base
** 
** Made by charles-edouard vanet
** Login   <vanet_c@epitech.net>
** 
** Started on  Sun Nov 11 18:35:38 2012 charles-edouard vanet
** Last update Thu Dec  6 16:10:31 2012 charles-edouard vanet
*/

#include	<stdlib.h>
#include	"my.h"

int	get_power_base(int nb, char *base)
{
  int	idx;
 
  idx = 0;
  while (nb / my_strlen(base) >= 1)
    {
      idx = idx + 1;
      nb = nb / my_strlen(base);
    }
  return (idx);
}

void	positive_nbr_base(int nb, int pbase, char *base, char *buffer)
{
  int	digit;
 
  if (nb < my_strlen(base) && !(pbase > get_power_base(nb, base)))
    {
      buffer[0] = base[nb];
      buffer = buffer + 1;
    }
  else
    {
      if (pbase > get_power_base(nb, base))
	{
	  buffer[0] = base[0];
	  buffer = buffer + 1;
	  positive_nbr_base(nb, pbase - 1, base, buffer);
	}
      else
	{
	  digit = nb / (my_power_rec(my_strlen(base), pbase));
	  buffer[0] = base[digit];
	  buffer = buffer + 1;
	  positive_nbr_base(nb - digit * my_power_rec
			    (my_strlen(base), pbase), pbase - 1, base, buffer);
	}
    }
}

int	nbr_base(int nb, char *base, char *buffer)
{
  if (nb < 0)
    {
      buffer[0] = '-';
      buffer = buffer + 1;
      nb = -nb;
    }
  positive_nbr_base(nb, get_power_base(nb, base), base, buffer);
  return (nb);
}

char	*my_convert_base(char *nbr, char *base_from, char *base_to)
{
  int	nb_base10;
  char	*buffer;
 
  buffer = malloc(50);
  nb_base10 = my_getnbr_base(nbr, base_from);
  nbr_base(nb_base10, base_to, buffer);
  return (buffer);
}
